<?php
declare (strict_types=1);

namespace app\admin\http\middleware;

use app\common\enum\SysEnum;
use think\facade\Cache;

/**
 * 初始化验证中间件
 * Class InitMiddleware
 * @package app\adminapi\http\middleware
 */
class InitMiddleware
{
    /**
     * @notes 初始化
     * @param $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        self::ipLimiting($request);
        $request->uid = 0; //未登录
        $request->auth = null; //无账户信息
        return $next($request);
    }

    /**
     * ip限流
     * @param object $request
     */
    public static function ipLimiting($request)
    {
        $key = $request->ip() . '-' . $request->baseUrl();
        if ($num = Cache::get($key)) {
            if ($num > SysEnum::RATE_LIMITING) {
                tips('请求频繁');
            }
            Cache::inc($key);
        } else {
            Cache::set($key, 1, 5);
        }
    }
}